package org.ourgrid.broker.business.schedulerdata.executor;

import java.util.ArrayList;
import java.util.List;

import org.ourgrid.broker.business.schedulerdata.SchedulerData;
import org.ourgrid.broker.response.GetFilesMessageHandleResponseTO;
import org.ourgrid.common.FileTransferInfo;
import org.ourgrid.common.internal.IResponseTO;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class GetFilesExecutor extends AbstractSchedulerDataExecutor {
	
	/**
	 * <GET_FILES workerID='String' requestID='long'>
	 *    1..n <FILE transferHandleID='long' filePath='String'/> 
	 * </GET_FILES> 
	 */
	public List<IResponseTO> execute(SchedulerData command) {
		List<IResponseTO> responses = new ArrayList<IResponseTO>();
		
		Document logDocFile = super.getXMl(command.getXml());
		
		Element element = logDocFile.getDocumentElement();
		
		String workerID = element.getAttribute("workerID");
		long requestID = Long.valueOf(element.getAttribute("requestID"));
		
		int size = element.getElementsByTagName("FILE").getLength();
		FileTransferInfo[] files = new FileTransferInfo[size];
		
		FileTransferInfo info = null;
		long transferHandleID = 0;
		String filePath = null;
		
		for (int i = 0; i < size; i++) {
			transferHandleID = Long.valueOf(element.getElementsByTagName("FILE").item(i).getAttributes().
									getNamedItem("transferHandleID").getNodeValue());
			filePath = element.getElementsByTagName("FILE").item(i).getAttributes().
							getNamedItem("filePath").getNodeValue();
			
			info = new FileTransferInfo(transferHandleID, filePath);
			files[i] = info;
		}
		
		GetFilesMessageHandleResponseTO to = new GetFilesMessageHandleResponseTO(requestID, 
				getAddress(workerID), files);
		
		responses.add(to);
	
		
		return responses;
	}
	
}
